package com.dao;

import com.sun.xml.internal.bind.v2.TODO;
import entity.UserEntity;
import org.hibernate.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import vo.Pager;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * Created by john on 2016/4/24.
 */
public abstract class BaseDao<T> {
    private Class<T> entityClass;
    @Autowired
    private HibernateTemplate hibernateTemplate;

    public BaseDao(){
        //region 获得泛型的类型
        Type genType  =getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType ).getActualTypeArguments();
        entityClass = (Class) params[0];
        //endregion 获得泛型的类型
    }


    protected HibernateTemplate getHibernateTemplate(){
        return hibernateTemplate;
    }
    protected Session getSession(){
        return hibernateTemplate.getSessionFactory().getCurrentSession();
    }

    protected Query createQuery(String hql, Object... paramValues){
        Query query = getSession().createQuery(hql);
        for (int i=0;i<paramValues.length;i++){
            query.setParameter(i,paramValues[i]);
        }
        return query;
    }

    protected T load(Serializable id){
        return (T)getSession().load(entityClass,id);
    }

    protected T get(Serializable id){return (T)getSession().get(entityClass,id);}

    protected void save(T entity){
        getSession().save(entity);
    }
    protected long count(String sql,Object... paramValues){
        return (Long)find(sql,paramValues).get(0);
    }

    protected void delete(T entity){
        getSession().delete(entity);
    }
    protected void update(T entity){
        getSession().update(entity);
    }
    protected List find(String hql, Object... paramValues){
        return getHibernateTemplate().find(hql,paramValues);
    }

    protected Pager pagedQuery(Pager pager, String hql, Object... paramValues){
        String countString = "select count(*) "+hql;
        Long total = (Long)find(countString,paramValues).get(0);
        pager.setTotal(total.intValue());

        Query query = createQuery(hql,paramValues);
        int startIndex = 0;
        if(pager.getPage()>1){
            startIndex = (pager.getPage()-1)*pager.getPageSize();
        }
        List list = query.setFirstResult(startIndex).setMaxResults(pager.getPageSize()).list();
        pager.setRows(list);
        return pager;
    }

}
